package com.quark.service.system;

import com.quark.mapper.system.SysRoleMenuMapper;
import com.quark.model.system.role.SysRoleMenu;
import com.quark.service.redis.RedisService;
import com.quark.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 张高昌
 * @version 版本
 * @date 2021/11/11 16:11
 * @description: 功能描述
 */
@Service
@RequiredArgsConstructor
public class RoleMenuService {

    private final SysRoleMenuMapper sysRoleMenuMapper;

    private final RedisService redisService;

    public boolean authorize(int rId, String rules) {
        sysRoleMenuMapper.deleteByPrimaryRid(rId);
        List<String> list = Arrays.asList(rules.split(",")).stream().map(s -> (s.trim())).collect(Collectors.toList());
        List<SysRoleMenu> roleMenus = new LinkedList<>();
        for (String menuId : list) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRId(rId);
            sysRoleMenu.setMId(Integer.valueOf(menuId));
            roleMenus.add(sysRoleMenu);
        }
        sysRoleMenuMapper.batchAdd(roleMenus);
        Long userId = SecurityUtils.getUserId();
        //删除用户的菜单
        redisService.del("sys_menu_user_router:" + userId);
        //删除用户的权限
        redisService.del("sys_user_authorities:" + userId);

        return true;
    }
}
